from typing import List, Optional
from getcamerainfo import get_rect_info
import json

def create_video_config(
    # 必需参数
    video_path: str,
    list_pts_blue: List[float],
    position_ns: str,
    traffic_light_box: List[int],
    
    # 可选参数（带默认值）
    algorithm_list: Optional[List[str]] = None,
    bmodel_detector_dir: str = "/home/linaro/cw/yolov5n_1684x_f16.bmodel",
    bmodel_extractor_dir: str = "/home/linaro/cw/osnet19296.bmodel",
    classnames_dir: str = "/home/linaro/cw/sophon-demo_v0.2.5_c7c94bb_20241019/sample/YOLOv5/cpp/yolov5_bmcv/coco.names",
    config_dir: str = "/home/linaro/cw/sophon-demo_v0.2.5_c7c94bb_20241019/sample/DeepSORT/cpp/deepsort_bmcv/deep_sort.yaml",
    frame_interval: int = 5,
    device_name : str ="0",
    save_pic : str ="1"
) -> dict:
    """
    创建视频分析配置结构体
    
    参数验证：
    - traffic_light_box 必须包含4个整数
    - list_pts_blue 必须包含偶数个坐标点
    - position_ns 应为标准方位缩写
    
    示例：
    >>> config = create_video_config(
    >>>     video_path="/data/videos/crossing.mp4",
    >>>     list_pts_blue=[23.0, 166.0, 566.0, 166.0, 566.0, 311.0, 23.0, 311.0],
    >>>     position_ns="north",
    >>>     traffic_light_box=[464, 128, 480, 160]
    >>> )
    """
    # 参数验证
    if len(traffic_light_box) != 4:
        raise ValueError("交通灯区域坐标需要4个整数值 [x1, y1, x2, y2]")
        
    if len(list_pts_blue) % 2 != 0:
        raise ValueError("人行道坐标应为偶数个数值，格式：[x1,y1, x2,y2,...]")
        
    if not all(isinstance(x, (int, float)) for x in list_pts_blue):
        raise ValueError("坐标点必须为数字类型")
    
    # 设置默认算法列表
    algorithm_list = algorithm_list or ["garbage", "garbage"]
    
    return {
        "video_path": video_path,
        "list_pts_blue": list_pts_blue,
        "position_ns": position_ns.lower(),  # 统一转小写
        "traffic_light_box": traffic_light_box,
        "algorithm_list": algorithm_list,
        "bmodel_detector_dir": bmodel_detector_dir,
        "bmodel_extractor_dir": bmodel_extractor_dir,
        "classnames_dir": classnames_dir,
        "config_dir": config_dir,
        "frame_interval": max(1, frame_interval),  # 保证最小间隔为1
        "camera_id": device_name,
        "save_pic" : save_pic
    }


#根绝摄像头名称和地址创建配置文件
def gen_sdkconfig(movie_path, device_name,save_pic_=0):
    device_info = get_rect_info(device_name)
    print("device_info: ", device_info)
    # 检查视频路径是否以 crossing.mp4 结尾
    if movie_path.endswith("crossing.mp4"):
        # print("end with")
        frame_interval = 1
    else:
        # print("not end with")
        frame_interval = 6
    # print("frame_interval: ",frame_interval)
    configs = create_video_config(video_path=movie_path, list_pts_blue=device_info[1], position_ns="north",
                                  traffic_light_box=device_info[0], device_name=device_name,
                                  frame_interval=frame_interval, save_pic=str(save_pic_))

    save_path = "/home/linaro/.vs/sdk-test/sdk_config.json"
    try:
        with open(save_path, 'w', encoding='utf-8') as f:
            json.dump(configs, f, ensure_ascii=False, indent=4)
        print(f"配置文件已成功保存到 {save_path}")
    except Exception as e:
        print(f"保存配置时出错: {e}")


if __name__ == '__main__':
    movie_path = "/data/mn4/chunk_0001/chunk_0001.mp4"
    device_name = "chunk_0001"
    print(gen_sdkconfig(movie_path, device_name))
    # gen_sdkconfig(task["video_path"], get_parent_dir(task["video_path"]))